<template>
    <div class="dhzn_goodsmaterial">
        <!-- 内容层 -->
        <div v-if="pageingstate !== 2">
            <!-- 查询 -->
            <div class="d_m-c-query mb10">
                <el-carousel :interval="4000" type="card" height="170px" class="d_mcq-carousel">
                    <el-carousel-item v-for="item in basiclist" :key="item.id">
                        <img :src="item.imageurl" class="medium">
                    </el-carousel-item>
                </el-carousel>
                <span class="bc4a wh br5 f14 p5 cup" @click="pageingstate=2;imageurl=''">添加规格</span>
            </div>

            <!-- 数据列表 -->
            <div class="d_m-c-list f14">
                <!-- 数据表 -->
                <table class="d_mcl-tabel tc">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>图片</th>
                            <th>对应商品</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item,key) in basiclist" :key="key">
                            <td>{{item.id}}</td>
                            <!-- 图片的预览 -->
                            <td class="f0 pt5 pb5">
                                <el-popover placement="top" popper-class="d_gld-t-popover" trigger="click" v-model="item.visible">
                                    <img :src="item.imageurl">
                                    <img slot="reference" :src="item.imageurl">
                                </el-popover>
                            </td>
                            <td>{{item.goodsid | filname}}</td>
                            <td>
                                <button type="button" class="wh bc4a br5 pt5 pb5" @click="dialogalter=true;for(var i in bannerupdate)bannerupdate[i]=item[i],bannerupdate.key=key"><i class="el-icon-edit-outline"></i>修改</button>
                                <button type="button" class="wh bcfd br5 pt5 pb5" @click="requestdelete(item.id,key)">删除<i class="el-icon-delete"></i></button>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <div class="d_rj-block mt20">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-size="pagesize"
                        layout="total, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>
            </div>

            <!-- 修改的弹出层 -->
            <el-dialog 
                title="修改图片"
                :visible.sync="dialogalter"
                width="430px">

                <el-form label-width="80px">
                    <el-form-item label="上传图片">
                        <el-upload
                            action="/api/file/upload"
                            ref="upload"
                            :headers="headers" 
                            name="files"
                            list-type="picture-card"
                            :on-success="uploadimage"
                            :on-preview="imgpreview"
                            :limit="1">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                    </el-form-item>
                </el-form>

                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogalter=false" size="mini">取消</el-button>
                    <el-button type="primary" @click="requestupdata" size="mini">更新</el-button>
                </span>
            </el-dialog>

        </div>
        <!-- 添加轮播图片 -->
        <div class="d_v-add" v-else>
            <div class="d_v-a-title bb1 mb10"><span class="wh bc4a dib br5 p5 mb10 f14 cup" @click="pageingstate = 0">返回列表</span></div>
            <span class="f14 ff53">*直接上传图片提交即可</span>
            <el-row class='df mt10'>
                <el-col :span="2" class="f14 g3 mta">
                    <el-button size="mini" type="primary" class="mta" @click="addbanner">提交</el-button>
                </el-col>
                <el-col :span="6">
                    <el-upload
                        action="/api/file/upload"
                        :headers="headers" 
                        name="files"
                        list-type="picture-card"
                        :on-success="uploadimage"
                        :on-preview="imgpreview"
                        :limit="1">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script>
let axios = require('axios')
let that
import {formatDate} from '../../js/time.js'
export default {
    components: {},
    data() {
        return {
            id: '',                             //路由传值
            token: '',                          //身份验证
            headers: '',                        //上传图片组件的请求头，在mouted中赋的值
            pageingstate: 0,                    //页面切换分页运行函数的状态管理
            goodsname: '',
            basiclist: [],
            // 查询条件绑定对象
            selectquery: {
                anonymous: '',
            },
            // 修改轮播图上传的图片
            bannerupdate:{
                id: '',
                imageurl: '',
                goodsid: '',
                key: ''
            },
            // 添加轮播图
            imageurl: '',
            dialogImageUrl: "",
            dialogVisible: false,
            dialogalter: false,
            goodsname: '',
            filtercontent: [],
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,						   //总条数
        };
    },
    filters:{
        filname(type){
            that.goodsname.forEach((item)=>{
                type===item.id ? type = item.name : '';
            })
            return type
        },
    },
    computed: {},
    watch: {},
    methods: {
        // 单页条数
        handleSizeChange(val) {
            // console.log(`每页: ${val}条数据`);
            let that = this;
            that.pagesize = val;
            that.goodsActivity()
        },

        //分页的跳页函数
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            let that = this;
            that.currentPage = val;
            that.goodsActivity()
        },

        // 增加
        addbanner(){
            if(that.imageurl !== ""){
                let data = {goodsid:that.id,imageurl:that.imageurl}
                axios({
                    method: "post",
                    url: "/api/goodsBanner/add",
                    headers: {
                        "Content-Type": "application/json",
                        "authorization": `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: JSON.stringify(data)
                }).then( resp=>{
                    console.log(resp)
                    if(resp.data.message === '请求成功'){
                        data.id = resp.data.data;
                        that.basiclist < that.pagesize ? (
                        that.basiclist.push(data),
                        that.total += 1) : '';
                        that.pageingstate = 0;
                        this.$message({
                            message: "修改成功",
                            type: "success"
                        })
                    }else{this.$message.error("更新失败！请刷新或重新登录后再次提交")}

                }).catch( err=> {console.log(err)})
            }else{this.$message.error("没有图片可以更新，请上传图片后再更新")}
        },

        // 删除评价图片
        requestdelete(id,key){
            let that = this;
            let updata = JSON.stringify({id: id});
            that.$confirm('此操作将永久删除该文件, 是否继续?', '提示',{
                confirmButtonText:'确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(()=>{
                axios({
                    method: 'post',
                    url: '/api/goodsBanner/delete',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=> {
                    console.log(resp)
                    if(resp.data.data === '删除成功！'){
                        that.basiclist.splice(key,1);
                        that.total--
                    }
                }).catch( err=> {console.log(err)})

                this.$message({
                    type: 'success',
                    message: '删除成功'
                })
            }).catch(()=>{
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },

        // 修改轮播图
        requestupdata(){
            if(that.bannerupdate.imageurl !== ""){
                let data = {id:that.bannerupdate.id,imageurl:that.bannerupdate.imageurl,goodsid:that.bannerupdate.goodsid};
                console.log(data)
                axios({
                    method: "post",
                    url: "/api/goodsBanner/update",
                    headers: {
                        "Content-Type": "application/json",
                        "authorization": `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: JSON.stringify(data)
                }).then( resp=> {
                    console.log(resp)
                    if(resp.data.message === "请求成功"){
                        this.$message({
                            message: "轮播图更新成功",
                            type: "success"
                        })
                        this.$refs.upload.clearFiles()
                        that.basiclist[that.bannerupdate.key].imageurl = data.imageurl;
                        that.dialogalter = false;
                    }else{this.$message.error("更新失败！请尝试刷新页面(F5)")}
                })
            }else{this.$message.error("请在图片上传成功后点击更新")}
        },

        // 评价图片
        goodsActivity(){
            let that = this;
            let data = {current: that.currentPage,size:that.pagesize,goodsid:that.id};
            // let state = that.selectquery.anonymous;
            that.selectquery.anonymous !== '' ? data.anonymous = that.selectquery.anonymous : '';
            let updata = JSON.stringify(data);
            axios({    
                method: 'post',
                url: '/api/goodsBanner/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> { 
                console.log("轮播图",resp)
                that.basiclist = resp.data.data;
                that.total = resp.data.code;
                if(that.pageingstate === 1){
                    resp.data.code !== 0 ? (
                        this.$message({
                            message: '为您找到'+resp.data.code+'条订单',
                            type: 'success'
                        })
                    ) : (this.$message('没有符合条件的订单'))
                    
                }
            }).catch( err=>{console.log(err)})
        },

        // 取消查询
        abolish(query){
            this.$refs[query].resetFields()
        },

        // 成功上传图片
        uploadimage(response,file,fileList){
            console.log(response,file,fileList)
            this.$message({
                message: "图片上传成功",
                type: "success"
            })
            if(that.pageingstate === 2){   
                that.imageurl = 'http://dzy.dpyun.site/upload/images/' + response.data[0];
            }else{
                that.bannerupdate.imageurl = 'http://dzy.dpyun.site/upload/images/' + response.data[0];
            }
            console.log(that.imageurl,that.bannerupdate.imageurl)
        },

        // 图片预览
        imgpreview(){
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },

        //拿token
        newtoken(){
            let that = this;
            let axios = require('axios')
			let loguser = JSON.parse(sessionStorage.getItem('updata'))
			let data = {username:loguser.username, password:loguser.password};
			let updata = JSON.stringify(data);
			axios({
				method: 'post',
				url: '/api/getAuthority/manager',
				headers: { 'Content-Type': 'application/json' },
				data: updata
			})
			.then( resp=> {
                that.token = resp.data.data;
                sessionStorage.setItem("token", JSON.stringify(resp.data.data))
                that.headers = {
                    // 'Content-Type': 'application/json',
                    'authorization': `Bearer ${resp.data.data}`
                }
                setTimeout(()=>{
                    that.goodsActivity()
                },300)
			}).catch( err=> {})
        }
    },
    created() {},
    mounted() {
        let that = this;
        that.id = that.$route.params.aid;
        that.goodsname = JSON.parse(sessionStorage.getItem('goodsdata'))
        that.newtoken()
    },
    beforeCreate() {
        that = this;
    },
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
.dhzn_goodsmaterial{
    height: calc(100% - 51px);
}
/* 内容查询、列表和分页 */
.d_m-content{
    height: 100%;
}
/* 查询 */
.d_m-c-query{
    display: flex;
    justify-content: space-between;
}
.d_m-c-query span{
    height: 20px;
    align-self: center;
}
/* .d_mcq-form .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
    margin: 0;
} */

/* 表单 */
.d_m-c-list{
    display: flex;
    flex-wrap: wrap;
    height: calc(100% - 240px);
}
.d_mcl-tabel{
    width: 100%;
    color: #666666;
    border-collapse: collapse;
    border-top: 1px solid #e0e0e0;
    border-right: 1px solid #e0e0e0;
}
.d_mcl-tabel thead tr, .d_mcl-tabel tbody tr:hover{
    background-color: #F2F2F2;
}
.d_mcl-tabel tr th,.d_mcl-tabel tr td{
    height: 50px;
    border-bottom: 1px solid #e0e0e0;
    border-left: 1px solid #e0e0e0;
}
.d_mcl-tabel tr td img{
    max-width: 120px;
    max-height: 80px;
}
.d_rj-block{
    margin-top: auto;
}

/* 轮播图 */
.el-carousel{
    width: 50%;
    margin: 0 auto;
}
.el-carousel__item img {
    width: 100%;
    height: 100%;
    color: #475669;
    font-size: 14px;
    opacity: 0.75;
    line-height: 200px;
    margin: 0;
}

.el-carousel__item:nth-child(2n) {
    background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n+1) {
    background-color: #d3dce6;
}
</style>